package com.qiangzhi.controller.common;

import com.qiangzhi.constant.DefaultDataConstant;
import com.qiangzhi.pojo.dto.UserDTO;
import com.qiangzhi.pojo.dto.UserInfoDTO;
import com.qiangzhi.pojo.po.UserPO;
import com.qiangzhi.pojo.vo.UserVO;
import com.qiangzhi.properties.JwtProperties;
import com.qiangzhi.result.Result;
import com.qiangzhi.service.CommonService;
import com.qiangzhi.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 公共接口
 */
@RestController
@RequestMapping("/common/info")
@Api(tags = "公共接口接口")
@Slf4j
public class CommonController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private CommonService commonService;

    /**
     * 教务系统登录
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("教务系统登录")
    public Result<UserVO> login(@Validated @RequestBody UserDTO userDTO) {
        log.info("登录：{}", userDTO);

        UserPO userPO = commonService.login(userDTO);

        // 登录成功 生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(DefaultDataConstant.DEFAULT_JWT_CLAIMS, userPO.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserVO userVO = UserVO.builder()
                .id(userPO.getId())
                .name(userPO.getName())
                .identify(userDTO.getIdentify())
                .token(token).build();

        return Result.success(userVO);
    }

    /**
     * 根据用户id修改用户密码
     *
     * @param userDTO
     * @return
     */
    @PutMapping("/updatePassword")
    @ApiOperation("用户修改密码")
    public Result updatePassword(@Validated @RequestBody UserDTO userDTO) {
        log.info("修改密码：{}", userDTO);
        commonService.updatePassword(userDTO);
        return Result.success();
    }

    /**
     * 根据jwt解析出的id编辑个人信息
     *
     * @param userInfoDTO
     * @return
     * @throws IOException
     */
    @PutMapping("/updateInfo")
    @ApiOperation("编辑个人信息")
    public Result updateInfo(@Validated UserInfoDTO userInfoDTO) throws IOException {
        log.info("编辑个人信息：{}", userInfoDTO);
        commonService.updateInfo(userInfoDTO);
        return Result.success();
    }

}
